package com.marktotop.file.controller;

import com.marktotop.file.entity.TbFile;
import com.marktotop.file.exception.SystemException;
import com.marktotop.file.response.ResultBean;
import com.marktotop.file.service.FastdfsService;
import com.marktotop.file.service.TbFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Date;

/**
 * 文件处理
 * @author WXLD
 * @data 2021/4/16 - 9:11
 */
@RestController
@CrossOrigin
@Api(tags = "文件管理接口")
@Slf4j(topic = "file")
@RequestMapping(value = "/api")
public class FastdfsController {

    @Autowired
    private FastdfsService fastdfsService;

    @Autowired
    private TbFileService tbFileService;

    /**
     * 上传图片，支持 jpeg/ png/ bmp/ gif
     * @param img
     * @return
     */
    @RequestMapping(value = "/uploadImg",method = RequestMethod.POST)
    @ApiOperation(value = "图片上传",notes="上传图片,支持 jpeg/png/bmp/gif,post方式")
    public ResultBean uploadImg(MultipartFile img) throws SystemException {
        // 获取文件名称
        String filename = img.getOriginalFilename();
        /*传入 文件名、文件*/
        String imageUrl = fastdfsService.uploadImage(filename, img);
        if (imageUrl != null){
            return ResultBean.ok().data("imageUrl",imageUrl).message("上传图片成功!");
        }
        return ResultBean.error().message("上传图片失败，请重试！");

    }

    /**
     * 文件上传
     * @param file 100MB以内
     * @return
     */
    @RequestMapping(value = "/uploadFile",method = RequestMethod.POST)
    @ApiOperation(value = "文件上传",notes="上传文件,post方式")
    public ResultBean uploadFile(@RequestParam("file") MultipartFile file) throws SystemException {
        String filename = file.getOriginalFilename();
        String fileUrl = fastdfsService.uploadFile(filename, file);
        if (fileUrl != null){
            return ResultBean.ok().data("fileUrl",fileUrl).message("文件上传成功!");
        }
        return ResultBean.error().message("文件上传失败，请重试！");

    }


    /**
     * 实现下载功能
     * @param fileId
     * @return
     */
    @RequestMapping(value = "/download",method = RequestMethod.GET)
    @ApiOperation(value = "文件下载",notes="文件下载,GET方式")
    public ResponseEntity<byte[]> download(@RequestParam("id") Integer fileId) throws IOException {

        // 需要在上传的时候保存文件名。下载的时候使用对应的格式
        TbFile tbFile = tbFileService.getOneById(fileId);
        byte[] downloadFile = fastdfsService.downloadFile(tbFile.getFileUrl());
        // 更新下载数量
        tbFile.setDownloadNum(tbFile.getDownloadNum()+1);
        Boolean updateDownloadCount = tbFileService.countDownloadNum(tbFile);
        if(!updateDownloadCount){
            return null;
        }
        String downloadName = tbFile.getFileName();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment;filename="+ new String(downloadName.getBytes("utf-8"), "iso-8859-1"));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Last-Modified", new Date().toString());
        headers.add("ETag", String.valueOf(System.currentTimeMillis()));
        String contentType = "application/octet-stream";
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .headers(headers)
                .body(downloadFile);
    }


    /**
     * 文件删除
     * @param fileId
     * @return
     * @throws SystemException
     */
    @RequestMapping(value = "/deleteFile",method = RequestMethod.DELETE)
    @ApiOperation(value = "文件删除",notes="文件删除方法,DELETE方式")
    public ResultBean deleteFile(@RequestParam("id") Integer fileId) throws SystemException {
        //  拿到删除对象
        TbFile oneById = tbFileService.getOneById(fileId);
        if(oneById == null){
            return ResultBean.error().message("未找不到该文件，请刷新后重试 ！！");
        }
        int i = fastdfsService.deleteFile(oneById);
        if (i == 1){
            return ResultBean.ok().message("文件删除成功！");
        }
        return ResultBean.error().message("找不到节点或文件！！");

    }

}
